package io.renren.sf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.*;
import io.renren.sf.dao.CbBasisStrokesFormworkDao;
import io.renren.sf.entity.CbBasisStrokesEntity;
import io.renren.sf.entity.CbBasisStrokesFormworkEntity;
import io.renren.sf.entity.CbStandardBrushEntity;
import io.renren.sf.feign.OssFeign;
import io.renren.sf.service.CbBasisStrokesFormworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;


@Service("cbBasisStrokesFormworkService")
public class CbBasisStrokesFormworkServiceImpl extends ServiceImpl<CbBasisStrokesFormworkDao, CbBasisStrokesFormworkEntity> implements CbBasisStrokesFormworkService {
    @Autowired
    private OssFeign ossFeign;

    @Override
    public String createJbbhmbZip() {
        // 获取标准笔画的所有记录
        List<CbBasisStrokesFormworkEntity> jbbhmbList = this.baseMapper.selectJbbhmbList();
        if (CollectionUtils.isEmpty(jbbhmbList)) {
            return "基本笔画模板不存在";
        }
        for (CbBasisStrokesFormworkEntity basisStrokesFormworkEntity : jbbhmbList) {
            // 下载基本笔画视频
            List<CbBasisStrokesEntity> basisStrokes = basisStrokesFormworkEntity.getBasisStrokes();
            for (CbBasisStrokesEntity basisStroke : basisStrokes) {
                String wordVideo = basisStroke.getWordVideo();
                if (StringUtils.isEmpty(wordVideo)) {
                    return "存在标准笔法视频未添加";
                }
                String wordVideoSuffix = wordVideo.substring(wordVideo.lastIndexOf("."));
                String wordVideoMd5 = MD5.encrypt(wordVideo) + wordVideoSuffix;
                Download.download(wordVideo, wordVideoMd5, Constant.ZipBasisStrokes.PATH.getName());
            }
        }

        // 将e:\hanzhiZipStandardBrush\下的文件打成压缩包
        // 得到file数组
        File[] files = getFiles(Constant.ZipBasisStrokes.PATH.getName());
        String zipPath = Constant.ZipBasisStrokes.YSB.getName() + Constant.ZipBasisStrokes.ZIPNAME.getName() + ".zip";
        File zipFile = new File(zipPath); // zip存放路径
        ZipMultiFile.zipFiles(files, zipFile);
        R upload = ossFeign.uploadZip(zipPath);// 上传至oss
        return (String) upload.get("url");
    }

    private File[] getFiles(String path) {
        File dir = new File(path);
        return dir.listFiles();
    }
}